﻿using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static System.Net.WebRequestMethods;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;


namespace ArticleUploadBatch.WinUI.Services
{

    public class DayuArticleService
    {
        public string PublishUrl { get; set; }
        public string UserName { get; set; }
        public string Pwd { get; set; }
        public IWebDriver Driver { get; set; }

        public DayuArticleService(string userName,string pwd) 
        {
            this.PublishUrl = "https://mp.dayu.com/dashboard/article/write";
            this.Driver = new ChromeDriver();
            this.UserName= userName;
            this.Pwd = pwd;
          
            this.Driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);
            this.Driver.Manage().Window.Maximize();
        }

        public void UploadOne(string filePath, Action<string> writeLineLog)
        {
            IWebDriver driver = this.Driver;

            driver.Navigate().GoToUrl(this.PublishUrl);
            Thread.Sleep(2000);

            //如果要登陆就先登陆，直达登陆完成
            if (driver.Url.Contains("mp.dayu.com/?redirect_url"))
            {
                //大鱼号登陆

                //driver.SwitchTo().DefaultContent();
                driver.SwitchTo().Frame(driver.FindElement(By.TagName("iframe")));

                driver.FindElement(By.Name("login_name")).SendKeys(this.UserName);//账号
                driver.FindElement(By.Name("password")).SendKeys(this.Pwd);//密码

                //driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-confirm-info > span.web-login-confirm-info__checkbox"))
                //    .Click();//勾选复选框
                //driver.FindElement(By.CssSelector("#BD_Login_Form > div > article > article > div.web-login-union__login > div.web-login-union__login__form > div.web-login-union__login__form__content > article > div.web-login-account-password__password-input-wrapper > div > div > input"))
                //    .SendKeys(this.Pwd);//密码

                driver.FindElement(By.Id("submit_btn"))
                    .Click();//点击登陆

                while (true)
                {
                    if (driver.Url.Contains("mp.dayu.com/?redirect_url"))
                    {
                        Thread.Sleep(2000);
                    }
                    else
                    {
                        writeLineLog("登陆成功：");
                        break;
                    }
                }
            }

            //确定是发布文章
            if (driver.Url.Contains("dashboard/article/write"))
            {
                //单个文章上传
                string title = Path.GetFileNameWithoutExtension(filePath);
                writeLineLog("正在上传文章：" + title);
                //发布文章
                try
                {
                    //是否继续编辑按钮
                    driver.FindElement(By.CssSelector(".byte-drawer-mask"))
                   .Click();
                }
                catch (Exception)
                {
                }            
                if (System.IO.File.Exists(filePath))
                {

                    driver.FindElement(By.Id("title"))
                        .SendKeys(title);//输入标题
                    string content = System.IO.File.ReadAllText(filePath);

                    //切换焦点到mainFrame
                    driver.SwitchTo().DefaultContent();                   
                    driver.SwitchTo().Frame("ueditor_0");

                    driver.FindElement(By.CssSelector("body"))
                        .SendKeys(content);//输入文章内容
                    Thread.Sleep(2000);

                    //切换到原文档
                    driver.SwitchTo().DefaultContent();
                    // 上传封面图和正文中的图片
                    //string coverPath = Path.Combine(Directory.GetCurrentDirectory(), "holder.jpg");
                    //driver.FindElement(By.Name("cover")).SendKeys(coverPath);
                    //driver.FindElement(By.CssSelector(".ProseMirror img")).SendKeys(coverPath);
                    //滚动到底部
                    var jsReturnValue = (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript("window.scrollTo(0,document.body.scrollHeight);");
                    Thread.Sleep(1000);

                    //driver..execute_script("window.scrollTo(0,document.body.scrollHeight);")
                    driver.FindElement(By.CssSelector("body > div.container > div.w-contentbox > div > div:nth-child(2) > div > div.article-write_box.w-scrollbar > div.article-write_box-form > div.article-write_box-cover > div > div > div > div > div.article-write-article-cover_normal-options > div:nth-child(2) > div"))
                        .Click();//点击单封面
                    //driver.FindElement(By.CssSelector("body > div.container > div.w-contentbox > div > div:nth-child(2) > div > div.article-write_box.w-scrollbar > div.article-write_box-form > div.article-write_box-cover > div > div > div > div > div.article-write-article-cover_normal-options > div:nth-child(2)"))
                    //   .Click();//点击单封面按钮


                    //driver.FindElement(By.CssSelector("body > div.container > div.w-contentbox > div > div:nth-child(2) > div > div.article-write_box.w-scrollbar > div.article-write_box-opt > div > button:nth-child(6)"))
                    //    .Click();//点击预览
                    driver.FindElement(By.CssSelector("body > div.container > div.w-contentbox > div > div:nth-child(2) > div > div.article-write_box.w-scrollbar > div.article-write_box-opt > div > button:nth-child(8)"))
                        .Click();//点击保存

                    
                    Thread.Sleep(1000);

                    //driver.FindElement(By.CssSelector("#root > div > div > div.publish-footer > div > button:nth-child(3)"))
                    //    .Click();
                    //返回草稿
                    driver.Navigate().GoToUrl("https://mp.dayu.com/dashboard/draft?spm=a2s0i.db_material.menu.9.54603caacrR4VN");
                    Thread.Sleep(2000);

                    //接受alert
                    try
                    {
                        driver.SwitchTo().Alert().Accept();
                        Thread.Sleep(1000);
                    }
                    catch (Exception)
                    {

                    }
                   
                    //WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, 2));
                    ////Wait for the alert to be displayed
                    //wait.Until(ExpectedConditions.AlertIsPresent());

                    //Console.WriteLine(driver.SwitchTo().Alert().Text);//在接收消息前输出
                    //System.Threading.Thread.Sleep(1000);
                    //driver.SwitchTo().Alert().Accept();


                    writeLineLog("上传文章成功：" + title);
                }
            }
        }


        public void UploadMany(string[] filePathList,Action<string> writeLineLog)
        {         
            foreach (string filePath in filePathList)
            {
                this.UploadOne(filePath, writeLineLog);
            }
            writeLineLog("所有文章上传完成");
        }

        public void Quit()
        {
            this.Driver.Close();
            this.Driver.Quit();
        }


    }
}
